//
//  FirstViewController.swift
//  SwiftUI
//
//  Created by lvfeijun on 2021/5/12.
//  Copyright © 2021 lvfeijun. All rights reserved.
//

import UIKit

class FirstViewController: UIViewController,UITextFieldDelegate {
    var label:UILabel?
    var textField:UITextField?
    var textView:UITextView?
    //Timer
    var timer:Timer?
//    {
//        get{
//            if _timer == nil {
//                _timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { (timer) in
//                    let txt:Int? = Int(self.label?.text ?? "0")
//                    //            lable.text = self.getTimeText(time: txt!+1)
//                    self.label?.text = String(txt!+1)
//                }
//            }
//            return _timer
//        }
//    }
    func createTimer() {
        self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(runTimer), userInfo: nil, repeats: true)
        RunLoop.current.add(self.timer!, forMode: RunLoop.Mode.common)
        self.timer?.fireDate = NSDate.distantPast
    }
    func startTimer() {
        if self.timer==nil {
            self.createTimer()
        }
    } 
    func killTimer() {
        if self.timer != nil {
            if self.timer!.isValid {
                self.timer?.invalidate()
            }
            self.timer = nil
        }
        self.label?.text = "0"
    }
    @objc func runTimer() {
        let txt:Int? = Int(self.label?.text ?? "0")
        self.label?.text = String(txt!+1)
    }
    
    //compactMap函数,过滤不符合条件的
    func doCompactMap() {
        let nums = [1,nil,2,nil,3,4,5,6,nil,nil,7,nil]
        print(nums)
        //去nil
        let nums1 = nums.compactMap { (item) -> Int? in
            return item
        }
        print(nums1)
        print(nums.compactMap{return $0})
        //转字符
        let nums2 = nums1.compactMap { (item) -> String? in
            return "\(item)"
        }
        print(nums2)
        print(nums1.compactMap{return "\($0)"})
        //取能被3整除
        let nums3 = nums1.compactMap { (item) -> Int? in
            if item%3==0 {
                return item
            }else{
                return nil
            }
        }
        print(nums3)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        self.navigationItem.title = "首页"
        self.view.backgroundColor = UIColor.white;
//        self.doCompactMap()
        
        //view
        let view = UIView()
        self.view.addSubview(view)
        view.frame = CGRect(x:100,y:500,width:200,height:200)
//        view.backgroundColor = UIColor.red
        
        //旋转
        /*
         a    水平方向上的缩放因子
         b    水平方向上的斜切因子
         c    垂直方向上的斜切因子
         d    垂直方向上的缩放因子
         tx    水平方向上的位移因子
         ty    垂直方向上的位移因子
         */
        var transform = CGAffineTransform()
        transform.a = 1.0
        transform.b = 0.5
        transform.c = 0.5
        transform.d = 1.0
        transform.tx = 0.0
        transform.ty = 0.0
        view.transform = transform
        
        //阴影
        view.layer.shadowColor = UIColor.yellow.cgColor
        view.layer.shadowOffset = CGSize(width: 1, height: 1)
        view.layer.shadowOpacity = 0.45
        view.layer.shadowRadius = 5
        
        //渐变色
        let gradientLayer = CAGradientLayer()
        gradientLayer.frame = view.bounds
        
        let fromColor = UIColor.green.cgColor
        let minColor = UIColor.red.cgColor
        let toColor = UIColor.blue.cgColor
        
        gradientLayer.colors = [fromColor,minColor,toColor]
        gradientLayer.startPoint = CGPoint(x: 0, y: 0)
        gradientLayer.endPoint = CGPoint(x: 1, y: 1)
        gradientLayer.locations = [0,0.3,1]
        view.layer.addSublayer(gradientLayer)
        
        //获取屏幕大小
        let screenBounds:CGRect = UIScreen.main.bounds
        //获取屏幕大小（不包括状态栏高度）
        let viewBounds:CGRect = UIScreen.main.applicationFrame
        var x:CGFloat=0,y:CGFloat=viewBounds.minY+44,Screenwidth:CGFloat = viewBounds.width,_:CGFloat = CGFloat(screenBounds.height)
        
        //lable
        label = UILabel(frame: CGRect(x: x, y: y, width: Screenwidth, height: CGFloat(20)))
        self.view .addSubview(label!)
        label!.textColor = UIColor.black
        label!.font = UIFont.systemFont(ofSize: 10)
        label!.textAlignment = NSTextAlignment.center
        label!.numberOfLines = 0
        label!.backgroundColor = UIColor.red
        y += 20
        
        //button
        let button = UIButton(frame: CGRect(x: 0, y: y, width: Screenwidth, height: 40))
        self.view .addSubview(button)
        button.backgroundColor = UIColor.gray
        button.setTitle("开始", for: UIControl.State.normal)
        button.setTitle("暂停", for: UIControl.State.selected)
        button.addTarget(self, action: #selector(butttonClick(bt:)), for: UIControl.Event.touchUpInside)
        y += 40
        
        //textfield
        let textField = UITextField(frame: CGRect(x: x, y: y, width: Screenwidth, height: 40))
        self.view .addSubview(textField)
        textField.placeholder = "输入文字"
        textField.keyboardType = UIKeyboardType.URL
        textField.clearButtonMode = UITextField.ViewMode.whileEditing
        textField.delegate = self as UITextFieldDelegate;
        textField.borderStyle = UITextField.BorderStyle.line
        textField.returnKeyType = UIReturnKeyType.go
        textField.isSecureTextEntry = true
        self.textField = textField
        y += 40
        
        //textview
        let textview = UITextView(frame: CGRect(x: x, y: y, width: Screenwidth, height: 40))
        self.view.addSubview(textview)
        textview.backgroundColor = UIColor.green
        self.textView = textview
        y += 40
        
//        if let data:Array = UserDefaults.standard.value(forKey: "data") as! Array{
//            self.label?.text = data[0]
//            self.textField?.text = data[1]
//            self.textView?.text = data[3]
//        }
        let filePath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)[0] + "/data.dat"
        guard let data = NSKeyedUnarchiver.unarchiveObject(withFile: filePath) as? Data else{
            //处理
            return
        }
        
        do{
            let model = try PropertyListDecoder().decode(DataModel.self, from: data)
            self.label?.text = model.label
            self.textField?.text = model.textField
            self.textView?.text = model.textView
        }catch{
            print("ERROR data retriving from cache")
        }
        
        let nexBt = UIButton(frame: CGRect(x: x, y: y, width: Screenwidth, height: 40))
        self.view.addSubview(nexBt)
        nexBt.setTitle("下一步", for: UIControl.State.normal)
        nexBt.addTarget(self, action: #selector(nextClick), for: UIControl.Event.touchUpInside)
        nexBt.backgroundColor = UIColor.cyan
        
    }
    
    @objc func butttonClick(bt:UIButton) {
        bt.isSelected = !bt.isSelected
        if bt.isSelected {
            self.startTimer()
//            self.timer?.fire()
        }else{
            self.killTimer()
//            self.timer?.invalidate()
        }
//        bt.isSelected:(self.timer?.fire()):(self.timer?.timeInterva)
    }
    
    //时间转换
//    func getTimeText(time:Int) -> String {
//        var result:[String] = ["00","00","00"]
//        result[2] = String(time%60)
//        result[1] = String(time/60)
//        if Int(result[1])! > 59 {
//            result[0] = String(time/60)
//            result[1] = String(time%60)
//        }
//        return String(result[0]+":"+result[1]+":"+result[2])
//    }

    func textFieldShouldClear(_ textField: UITextField) -> Bool {
        print("textFieldShouldClear")
        return true
    }
    
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        print(string)
        return true
    }
    
    
    @objc func nextClick()  {
        let tableview = TableViewController()
        tableview.data = [self.label!.text,self.textField!.text,self.textView!.text] as! [String]
        if (self.navigationController != nil) {
            self.navigationController?.pushViewController(tableview, animated: true)
        }else{
            self.present(tableview, animated: true, completion: nil )
        }
        
//        self.navigationController?.pushViewController(tableview, animated: true)
    }
}
